package com.hqm.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hqm.meta.AccountRecord;
import com.hqm.meta.BuyMsg;
import com.hqm.meta.Product;
import com.hqm.meta.ShoppingInfo;
import com.hqm.meta.Transaction;
import com.hqm.meta.User;
import com.hqm.service.ProductService;
import com.hqm.service.TransactionService;

@Controller
public class ShoppingController {
	private static final Log logger = LogFactory.getLog(ShoppingController.class);
	
	@Resource
	ProductService productService;
	
	@Resource
	TransactionService transactionService;
	
	/**
	 * 跳转至帐务页
	 * 只有登录的买家才能访问
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/settleAccount", method = RequestMethod.GET)
	public String toShopingCart(HttpSession session) {
		logger.info("shoppingCart called");
		
		User user = (User)session.getAttribute("user");
		
		if (user != null && user.getUsertype() == 0) {
			return "settleAccount";
		} else {
			return new PageController().toLogIn();
		}
	}
	
	/**
	 * 处理买家购买请求
	 * @param shoppingInfos
	 * @param request
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/api/buy", method = RequestMethod.POST)
	public BuyMsg doShop(@RequestBody ShoppingInfo[] shoppingInfos,
			HttpServletRequest request, HttpSession session) {
		logger.info("doShop called");
		
		List<AccountRecord> buyList = new ArrayList<AccountRecord>();
		User user = (User)session.getAttribute("user");
		Integer userId = user.getId();
		
		//创建时间戳
		Date date = new Date();
		Long time = date.getTime();
		
		Transaction transaction = new Transaction();
		Boolean isAdd = false;
		
		//根据后台数据库交易记录，创建某一买家的购买清单
		TRX:
		for (ShoppingInfo shoppingInfo : shoppingInfos) {
			Integer productId = shoppingInfo.getId();
			Product product = productService.getProduct(productId);
			
			transaction.setContentid(productId);
			transaction.setUserid(userId);
			transaction.setPrice(product.getPrice());
			transaction.setTime(time);
			
			for (int i = 0; i < shoppingInfo.getNumber(); i++) {
				isAdd = transactionService.addtrx(transaction);
				if (!isAdd) {
					break TRX;
				}
			}
			
			AccountRecord accountRecord = new AccountRecord();
			accountRecord.setId(transaction.getContentid());
			accountRecord.setTitle(product.getTitle());
			accountRecord.setImage(product.getIcon());
			accountRecord.setBuyPrice(transaction.getPrice());
			accountRecord.setBuyNum(shoppingInfo.getNumber());
			accountRecord.setBuyTime(time);
			buyList.add(accountRecord);
		}
		
		logger.info("transaction finished");
		//返回购买信息
		BuyMsg buyMsg = new BuyMsg();
		if (isAdd) {
			buyMsg.setCode(HttpServletResponse.SC_OK);
			buyMsg.setMessage("购买成功");
			buyMsg.setResult(true);
			session.setAttribute("buyList", buyList);
//			session.setMaxInactiveInterval(0);
		} else {
			buyMsg.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			buyMsg.setMessage("购买失败");
			buyMsg.setResult(false);
			session.setAttribute("buyList", null);
		}
		
		return buyMsg;
	}
	
	/**
	 * 跳转至帐务页
	 * 只有登录的买家才能访问
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/account", method = RequestMethod.GET)
	public String toAccount(HttpSession session, Model model) {
		logger.info("toAccount called");
		
		User user = (User)session.getAttribute("user");
		if (user != null && user.getUsertype() == 0) {
			List<AccountRecord> buyList = new ArrayList<AccountRecord>();
			try {
				logger.info("trx");
				List<Transaction> transactions = transactionService.getTrx(user);
				logger.info("trxs");
				for (Transaction transaction : transactions) {
					Product product = productService.getProduct(transaction.getContentid());
					
					AccountRecord accountRecord = new AccountRecord();
					accountRecord.setId(product.getId());
					accountRecord.setImage(product.getIcon());
					accountRecord.setTitle(product.getTitle());
					accountRecord.setBuyTime(transaction.getTime());
					accountRecord.setBuyNum(transactionService.getProductBuyNum(product, user));
					accountRecord.setBuyPrice(transaction.getPrice());
					
					buyList.add(accountRecord);
				}
			} catch (Exception e) {
				buyList = null;
			}
			
			model.addAttribute("buyList", buyList);
			return "account";
		} else {
			return new PageController().toLogIn();
		}
	}
}
